package com.valsong.sandbox.mock.context;


import com.alibaba.jvm.sandbox.api.resource.ModuleEventWatcher;
import com.valsong.sandbox.mock.EventWatcherContext;
import com.valsong.sandbox.mock.EventWatcherProvider;
import com.valsong.sandbox.mock.LoggerAdjustment;
import com.valsong.sandbox.mock.MockConfig;
import com.valsong.sandbox.mock.MockConfigRepository;
import lombok.extern.slf4j.Slf4j;

import javax.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * InternalEventWatcherContext
 *
 * @author Val Song
 */
@Slf4j
public class InternalEventWatcherContext implements EventWatcherContext {

    private ModuleEventWatcher moduleEventWatcher;

    @Inject
    private MockConfigRepository mockConfigRepository;

    @Inject
    private EventWatcherProvider eventWatcherProvider;

    @Inject
    private LoggerAdjustment loggerAdjustment;

    @Override
    public void prepare(ModuleEventWatcher moduleEventWatcher, Map<String, String> param) {
        //调整日志级别
        loggerAdjustment.setLogLevel(param);
        this.moduleEventWatcher = moduleEventWatcher;
        mockConfigRepository.initMockConfigs(param);
    }

    @Override
    public List<MockConfig> register() {
        doRegister();
        return mockConfigRepository.findAllMockConfigs();
    }

    /**
     * 注册不同类型的MockConfig
     */
    private void doRegister() {

        List<MockConfig> mockConfigList = mockConfigRepository.findAllMockConfigs();

        log.info(" mockConfigList:[{}]", mockConfigList);

        if (mockConfigList == null || mockConfigList.isEmpty()) {
            return;
        }

        mockConfigList.stream()
                .filter(Objects::nonNull)
                .forEach(mp -> {
                    eventWatcherProvider.newEventWatcher(moduleEventWatcher, mp);
                });

    }

}
